package com.openspring.framework.jdbc.sql;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Select {
	
	private String tableName;
	private List<String> columns = new ArrayList<String>();
	private Map<String, String> primaryKeyColumns = new LinkedHashMap<String, String>();
	
	public Select setTableName(String tableName) {
		this.tableName = tableName;
		return this;
	}
	
	public Select addColumn(String columnName) {
		columns.add(columnName);
		return this;
	}

	public Select addPrimaryKeyColumn(String columnName) {
		addPrimaryKeyColumn(columnName, "?");
		return this;
	}
	
	public Select addPrimaryKeyColumn(String columnName, String valueExpression) {
		this.primaryKeyColumns.put(columnName, valueExpression);
		return this;
	}
	
	public String toSelect() {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT ");
		Iterator<String> iter = columns.iterator();
		while (iter.hasNext()) {
			sb.append(iter.next());
			if (iter.hasNext()) {
				sb.append(", ");
			}
		}
		sb.append(" FROM ").append(tableName);
		return sb.toString();
	}
	
	public String toSelectById() {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT ");
		Iterator<String> iter = columns.iterator();
		while (iter.hasNext()) {
			sb.append(iter.next());
			if (iter.hasNext()) {
				sb.append(", ");
			}
		}
		sb.append(" FROM ").append(tableName);
		if (!primaryKeyColumns.isEmpty()) {
			sb.append(" WHERE ");
		}
		Iterator<Map.Entry<String, String>> iter1 = primaryKeyColumns.entrySet().iterator();
		while (iter1.hasNext()) {
			Map.Entry<String, String> e = iter1.next();
			sb.append(e.getKey()).append(" = ").append(e.getValue());
			if (iter1.hasNext()) {
				sb.append(" AND ");
			}
		}
		return sb.toString();
	}
	
	public String toSelectCount() {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT COUNT(*) FROM ").append(tableName);
		return sb.toString();
	}
	
	public String toSelectCountById() {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT COUNT(*) FROM ").append(tableName);
		if (!primaryKeyColumns.isEmpty()) {
			sb.append(" WHERE ");
		}
		Iterator<Map.Entry<String, String>> iter = primaryKeyColumns.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> e = iter.next();
			sb.append(e.getKey()).append(" = ").append(e.getValue());
			if (iter.hasNext()) {
				sb.append(" AND ");
			}
		}
		return sb.toString();
	}
}
